package com.lecture.java8.excel.a0327;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.AbstractSheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.HashMap;
import java.util.Map;

public class MergeSameColumnStrategy extends AbstractSheetWriteHandler {
    private final int mergeColumnIndex; // 需要合并的列索引（从 0 开始）

    public MergeSameColumnStrategy(int mergeColumnIndex) {
        this.mergeColumnIndex = mergeColumnIndex;
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Sheet sheet = writeSheetHolder.getSheet();
        int lastRowNum = sheet.getLastRowNum(); // 获取最后一行索引

        if (lastRowNum < 1) return; // 只有一行或没有数据，不需要合并

        int startRow = 1; // 从第一行开始（跳过表头）
        String lastValue = getCellValue(sheet.getRow(startRow).getCell(mergeColumnIndex));

        for (int rowIndex = startRow + 1; rowIndex <= lastRowNum; rowIndex++) {
            Row row = sheet.getRow(rowIndex);
            String currentValue = getCellValue(row.getCell(mergeColumnIndex));

            if (!currentValue.equals(lastValue)) {
                if (rowIndex - 1 > startRow) {
                    sheet.addMergedRegion(new CellRangeAddress(startRow, rowIndex - 1, mergeColumnIndex, mergeColumnIndex));
                }
                startRow = rowIndex;
                lastValue = currentValue;
            }
        }
        // 处理最后一个合并区域
        if (lastRowNum > startRow) {
            sheet.addMergedRegion(new CellRangeAddress(startRow, lastRowNum, mergeColumnIndex, mergeColumnIndex));
        }
    }

    private String getCellValue(Cell cell) {
        if (cell == null) return "";
        if (cell.getCellType() == CellType.STRING.getCode()) {
            return cell.getStringCellValue();
        } else if (cell.getCellType() == CellType.NUMERIC.getCode()) {
            return String.valueOf(cell.getNumericCellValue());
        }
        return "";
    }
}
